<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_getQuickReportList"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="msgId"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd" code="drillReport:add"
          >新增演练</b-button
        >
        <b-button
          icon="delete"
          :disabled="!selectKeys?.length"
          @click="onDelete"
          code="drillReport:remove"
          >删除</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button
        @click="() => onView(record)"
        type="link"
        icon="detail"
        code="drillReport:query"
        >详情</b-button
      >
      <b-button
        @click="() => onPush(record, 'edit')"
        type="link"
        icon="detail"
        code="drillReport:pull"
        >推送</b-button
      >
      <b-button
        @click="() => onRecord(record)"
        type="link"
        icon="detail"
        :disabled="record.pushCount <= 0"
        code="drillReportPushTotalLog:query"
        >记录</b-button
      >
    </template>
    <template #info="{ record }">
      <div class="eewMessage">
        <div>
          <div style="flex: 1">震级：</div>
          <div style="flex: 2">{{ record.magnitude || '--' }}M</div>
        </div>
        <div>
          <div style="flex: 1">震中烈度：</div>
          <div style="flex: 2">{{ record.epiintensity || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">震源深度：</div>
          <div style="flex: 2">{{ record.focdepth || '--' }}km</div>
        </div>
        <div>
          <div style="flex: 1">震中经度：</div>
          <div style="flex: 2">{{ record.epilon || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">震中纬度：</div>
          <div style="flex: 2">{{ record.epilat || '--' }}°</div>
        </div>
        <div>
          <div style="flex: 1">震中地名：</div>
          <div style="flex: 2">{{ record.locname || '--' }}</div>
        </div>
      </div>
    </template>
    <template #drillProjectVOS="{ record }">
      <Tree
        style="height: 130px; overflow-y: auto"
        :tree-data="record.drillProjectVOS"
        defaultExpandAll
        :fieldNames="{
          children: 'children',
          title: 'name',
          key: 'key',
        }"
      >
        <template #title="{ dataRef, data }">
          <span v-if="data.children">{{ dataRef.name }}</span>
          <span
            v-else
            :style="{
              color: data.onlineStatus == '1' ? '#67C23A' : '#F56C6C',
            }"
          >
            {{ dataRef.name }}
          </span>
        </template>
      </Tree>
    </template>
  </ProTable>
  <FormModal :items="items">
    <template #details>
      <div class="modal_table_only">
        <ProTable
          :fetchListApi="_pushTotalLog"
          hideSearch
          :columns="modalColumns"
        >
          <template #pushBy="{ record }">
            <span style="color: #409eff">{{ record.pushBy }}</span>
          </template>
          <template #operation="{ record }">
            <b-button
              @click="() => onModalView(record)"
              type="link"
              icon="detail"
              >查看</b-button
            >
          </template>
        </ProTable>
      </div>
    </template>
  </FormModal>

  <FormModal2 :items="items">
    <template #details>
      <ProTable
        :fetchListApi="_getFailLog"
        hideSearch
        :height="200"
        :columns="pushColumns"
      >
        <template #pushStatus="{ record }">
          <span v-if="record.pushStatus == '1'" style="color: #67c23a"
            >成功</span
          >
          <span v-else style="color: #f56c6c">失败</span>
        </template>

        <template #onlineStatus="{ record }">
          <Tag :color="record.onlineStatus == 1 ? 'success' : 'error'">{{
            record.onlineStatus == 1 ? '在线' : '离线'
          }}</Tag>
        </template>
      </ProTable>
    </template>
  </FormModal2>

  <FormModal3 :items="formItems">
    <template #customFooter="{ modalType, formState, visible }">
      <template v-if="modalType.value == 'add'">
        <b-button
          @click="onSave(formState, visible, false)"
          :disabled="!mockData.length"
          >仅保存</b-button
        >
        <b-button
          @click="onSave(formState, visible, true)"
          :disabled="!mockData.length"
          >保存并推送</b-button
        >
        <b-button @click="oncancel(modalType, visible)">取消</b-button>
      </template>
      <template v-if="modalType.value == 'info'">
        <b-button @click="onEdit(modalType)">编辑</b-button>
      </template>
    </template>
    <template #details>
      <div class="custom_title">
        <div>
          信息接收对象(已选
          <span style="color: #409eff; font-weight: 600">{{
            mockData.length
          }}</span>
          个)
        </div>
        <div>
          <b-button :disabled="isInfo" icon="add" @click="onSelect"
            >新增</b-button
          >
        </div>
      </div>
      <div class="eewRehearsal_details">
        <Table
          ref="selectRef"
          :dataSource="mockData"
          :columns="selectColumns"
          class="device_table"
          :scroll="{ x: 500, y: cacheHeight || scrollHeight }"
        >
          <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'onlineStatus'">
              <Tag :color="text == 1 ? 'success' : 'error'">{{
                text == 1 ? '在线' : '离线'
              }}</Tag>
            </template>

            <template v-if="column.dataIndex === 'operation'">
              <b-button @click="onRemove(column, record)" :disabled="isInfo"
                >移除</b-button
              >
            </template>
          </template>
        </Table>
      </div>
    </template>

    <template #customBtn>
      <b-button :disabled="isInfo" @click="getRandomChinaCoordinate"
        >随机地址</b-button
      >
    </template>
  </FormModal3>

  <FormModal4 :items="items">
    <template #details>
      <FormItemRest>
        <ProTable
          :fetchListApi="getDevice"
          :height="600"
          :formCol="{ md: 24, lg: 18 }"
          :btnCol="{ md: 24, lg: 6 }"
          :columns="warnColumns"
          :row-selection="warnSelection"
          row-key="deviceId"
        >
          <template #onlineStatus="{ record }">
            <Tag :color="record.onlineStatus == 1 ? 'success' : 'error'">{{
              record.onlineStatus == 1 ? '在线' : '离线'
            }}</Tag>
          </template>
        </ProTable>
      </FormItemRest>
    </template>
    <template #customFooter="{ formState, visible }">
      <b-button @click="onSelected(visible)">确定</b-button>
    </template>
  </FormModal4>

  <FormModal5 :items="pushItems">
    <template #after-content="{ visible }">
      <div class="process">
        <Progress
          type="circle"
          :percent="num"
          v-show="+num.toFixed(0) < 100"
        ></Progress>
        <Result
          status="success"
          title="推送完成"
          v-show="+num.toFixed(0) >= 100"
        >
          <template #extra>
            <b-button @click="onBack(visible)">返回列表</b-button>
          </template>
        </Result>
      </div>
      <div class="info">
        <div class="title">
          <span>全部 {{ deviceInfo.length || 0 }}</span>
          <span>推送失败 {{ lose || 0 }}</span>
          <span>推送成功 {{ succeed || 0 }}</span>
        </div>
        <div class="content">
          <Table
            ref="selectRef"
            style="height: 100%"
            :dataSource="pushData"
            :scroll="{ y: 150 }"
            :columns="pushColumns2"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'pushStatus'">
                <span v-if="record.pushStatus == '1'" style="color: #67c23a"
                  >成功</span
                >
                <span v-else style="color: #f56c6c">失败</span>
              </template>
            </template>
          </Table>
        </div>
      </div>
    </template>
  </FormModal5>
</template>

<script setup lang="tsx">
import { computed, nextTick, onMounted, ref } from 'vue';
import { hasPermission } from '@/permission';
import {
  FormItemRest,
  Modal,
  Progress,
  Result,
  Space,
  Table,
  Tag,
  Tree,
  TreeSelect,
} from 'ant-design-vue';
import { concat, pick } from 'lodash-es';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToEnum, treeToArray } from '@/utils/utils';
import { getDictType } from '@/api/monitor';
import { saveRecord } from '@/api/notice';
import {
  getAddress,
  getDetails,
  getDevice,
  getEewPushIndex,
  getFailLog,
  getPushLog,
  getQuickReportList,
  handleAdd,
  handleDelete,
  handleEewPush,
} from '@/api/push';
import CustomTree from '../components/customTree.vue';
import { drillsStore } from '../store';

const scrollHeight = ref(0);

const typeEnum: any = ref();
const dictInit = () => {
  getDictType('device_operate_type').then((res) => {
    typeEnum.value = listToEnum(res.data as any, 'dictLabel', 'dictCode');
  });
};

dictInit();
const {
  refreshStore,
  deviceModeOptions,
  deviceModeEnum,
  getModelOptions,
  getModelEnum,
  projectList,
} = drillsStore();
const tableRef = ref();

const init = () => {
  refreshStore.quickReport();
};

init();

const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values, all) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '创建时间',
    dataIndex: 'createTime',
    isTime: true,
  },
  {
    title: '震中地名',
    dataIndex: 'locname',
    hideInTable: true,
  },
  {
    title: '演练地震事件信息',
    dataIndex: 'info',
    hideInSearch: true,
  },
  {
    title: '信息接收对象',
    dataIndex: 'drillProjectVOS',
    hideInSearch: true,
  },
  {
    title: '推送次数',
    dataIndex: 'pushCount',
    hideInSearch: true,
  },
  {
    title: '操作人',
    dataIndex: 'updateBy',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    width: 240,
  },
]);

const modalColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '推送人',
    dataIndex: 'pushBy',
    hideInSearch: true,
  },
  {
    title: '推送总数',
    dataIndex: 'totalCount',
    hideInSearch: true,
  },
  {
    title: '推送成功数',
    dataIndex: 'successCount',
    hideInSearch: true,
  },
  {
    title: '推送失败数',
    dataIndex: 'failCount',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    width: 80,
  },
]);

const pushColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'pushTime',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    hideInSearch: true,
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
    hideInSearch: true,
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
  },
  {
    title: '推送结果',
    dataIndex: 'pushStatus',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'onlineStatus',
    hideInSearch: true,
  },
]);

const selectColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    align: 'center',
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    align: 'center',
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
    align: 'center',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    customRender: ({ text }) => {
      return deviceModeEnum.value[text];
    },
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 80,
  },
]);

const warnColumns = computed<ProTableProps['columns']>(() => [
  {
    title: '项目名称',
    dataIndex: 'projectName',
    hideInSearch: true,
  },
  {
    title: '项目名称',
    dataIndex: 'projectId',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.projectId}
          fieldNames={{ value: 'id' }}
          placeholder='请选择'
          treeData={projectList.value}
          treeCheckable={true}
          maxTagCount={0}
          allowClear={true}
          showCheckedStrategy={TreeSelect.SHOW_ALL}
          maxTagPlaceholder={(omittedValues) => {
            if (omittedValues.length == 1) {
              return omittedValues[0].label;
            } else if (
              omittedValues.length == treeToArray(projectList.value).length
            ) {
              return '全部';
            } else {
              return '多项目';
            }
          }}
        >
          {{
            title: ({ label, type }: any) => {
              return type == '1' ? (
                <span style='color:#bababa'>{label}</span>
              ) : (
                label
              );
            },
          }}
        </TreeSelect>
      );
    },
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    hideInSearch: true,
  },
  {
    title: '设备序列号',
    dataIndex: 'code',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    valueEnum: {
      ...deviceModeEnum.value,
    },
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    valueEnum: {
      '1': '在线',
      '0': '离线',
    },
  },
  {
    title: '设备型号',
    dataIndex: 'modelId',
    hideInTable: true,
    valueEnum: {
      ...getModelEnum.value,
    },
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '',
    type: 'number',
    field: 'details',
  },
]);

const pushItems = computed<ProFormProps['items']>(() => []);

const formItems = computed<ProFormProps['items']>(() => [
  {
    label: '震中地名',
    type: 'input',
    field: 'locname',
    labelCol: { style: { width: '120px' } },
    rules: [{ required: true, message: '请输入震中地名', trigger: 'blur' }],
    wrapperCol: { span: 21 },
    colProps: {
      span: 21,
    },
  },
  {
    label: '',
    type: 'input',
    field: 'customBtn',
    wrapperCol: { span: 3 },
    colProps: {
      span: 3,
    },
  },
  {
    label: '震中经度(°)',
    type: 'input',
    field: 'epilon',
    rules: [{ required: true, message: '请输入震中经度', trigger: 'blur' }],
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '震中纬度(°)',
    type: 'input',
    field: 'epilat',
    rules: [{ required: true, message: '请输入震中纬度', trigger: 'blur' }],
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '震级(M)',
    type: 'number',
    rules: [{ required: true, message: '请输入震级', trigger: 'blur' }],
    field: 'magnitude',
    labelCol: { style: { width: '120px' } },
    props: {
      max: 12,
      min: 0,
    },
  },
  {
    label: '震源深度(km)',
    type: 'number',
    rules: [{ required: true, message: '请输入震源深度', trigger: 'blur' }],
    field: 'focdepth',
    labelCol: { style: { width: '120px' } },
  },
  {
    label: '',
    type: 'number',
    field: 'details',
    wrapperCol: { span: 24 },
    colProps: {
      span: 24,
    },
  },
]);
const { FormModal, open } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal2, open: open2 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});
const {
  FormModal: FormModal3,
  open: open3,
  formRef,
} = useFormModal({
  size: 'middle',
  column: 2,
});

const { FormModal: FormModal4, open: open4 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const { FormModal: FormModal5, open: open5 } = useFormModal({
  size: 'middle',
  formProps: {
    wrapperCol: { span: 24 },
  },
});

const onSelect = (record: any) => {
  console.log(mockData.value, 'mockData', 'recordrecordrecord');
  warnKeys.value = mockData.value.map((item) => item.deviceId);
  open4({
    title: '选择接收对象',
    modalType: 'add',
    defaultValue: {
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const warnKeys: any = ref([]);
const selectList = ref<object[]>([]);
const warnSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: warnKeys.value,
    onChange(values, all) {
      selectList.value = [...new Set(concat(all, selectList.value))];
      warnKeys.value = [...new Set(concat(values, warnKeys.value))];
    },
    onSelect(record, selected, selectedRows, nativeEvent) {
      if (selected) return;
      warnKeys.value = warnKeys.value.filter((a: any) => a !== record.deviceId);
      selectList.value = selectList.value.filter(
        (a: any) => a.deviceId !== record.deviceId,
      );
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected) return;
      warnKeys.value = warnKeys.value.filter(
        (a: any) => !changeRows.find((b) => b.deviceId == a),
      );
      selectList.value = selectList.value.filter(
        (a: any) => !changeRows.find((b: any) => b.deviceId == a.deviceId),
      );
    },
  };
});

const code = ref();

const onRecord = async (record: any) => {
  code.value = record.msgId;
  open({
    title: '推送记录',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  pushStatus: '',
  drillPushTotalId: '',
});
const onModalView = async (record: any) => {
  queryParams.value = {
    ...queryParams.value,
    ...pick(record, ['code', 'pushStatus', 'drillPushTotalId']),
  };
  open2({
    title: '气象演练推送设备列表',
    modalType: 'disabled',
    defaultValue: {
      ...record,
    },
    hideFooter: true,
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await handleDelete(selectKeys.value);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const _pushTotalLog = async (params: any) => {
  const res = await getPushLog(code.value, params);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};

const _getFailLog = async () => {
  const res = await getFailLog(queryParams.value);
  const { rows, total } = res;
  return {
    rows,
    total,
  };
};

const _getQuickReportList = async (queryParams: any) => {
  const res = await getQuickReportList(queryParams);
  const { rows, total } = res;
  const newRows = processData(rows);
  return {
    rows: newRows,
    total,
  };
};

const processData = (data: any) => {
  function processItem(item: any, depth = 0, str: any) {
    if (item[str] && item[str].length > 0) {
      item[str].forEach((subItem: any) => {
        if (str === 'children') {
          if (subItem.onlineStatus == '1') {
            subItem.name = subItem.code + '(在线)';
            item.onlineStatus = true;
          } else {
            subItem.name = subItem.code + '(离线)';
            if (!item.onlineStatus) {
              item.onlineStatus = false;
            }
          }
        }
        if (depth > 0 && subItem.children) {
          processItem(subItem, depth + 1, 'children');
        }
        if (depth > 1) delete subItem.children;
      });
    }
  }
  data.forEach((item: any) => {
    processItem(item, 1, 'drillProjectVOS');
  });
  return data;
};
const deviceInfo = ref([]);
const succeed = ref(0);
const lose = ref(0);
const reset = () => {
  pushData.value = [];
  deviceInfo.value = [];
  succeed.value = 0;
  lose.value = 0;
};
const onPush = async (record: any, type: string, id?: string) => {
  console.log(id, 'id');

  reset();
  if (type === 'edit') {
    Modal.confirm({
      title: '系统提示',
      content: `是否确认推送速报演练？`,
      onOk: async () => {
        const res = await getEewPushIndex({ msgId: record.msgId });
        if (res.code == 200) {
          const msgId = record.msgId;
          const drillPushTotalId = res.data;
          const result = await getDetails(record.msgId);
          deviceInfo.value = result.data.deviceInfo;
          deviceInfo.value.forEach(async (item: any) => {
            const res = await handleEewPush({
              msgId,
              code: item.code,
              deviceId: item.deviceId,
              drillPushTotalId,
            });
            if (res.code == 200) {
              num.value += 100 / sum.value;
              pushData.value.push(res.data);
              if (res.data.pushStatus === '1') {
                succeed.value++;
              } else {
                lose.value++;
              }
            }
            saveRecordFn(
              item,
              res,
              '推送',
              JSON.stringify({
                msgId,
                code: item.code,
                deviceId: item.deviceId,
                drillPushTotalId,
              }),
              '/drillReportPushLog',
            );
          });

          open5({
            title: '推送进度',
            modalType: 'disabled',
            hideFooter: true,
            serviceApi: async (params: any): Promise<any> => {},
          });
          tableRef.value.refresh();
        }
      },
    });
  } else {
    const res = await getEewPushIndex({ msgId: null });
    const drillPushTotalId = res.data;
    mockData.value.forEach(async (item: any) => {
      const res = await handleEewPush({
        msgId: id,
        code: item.code,
        deviceId: item.deviceId,
        drillPushTotalId,
      });
      if (res.code == 200) {
        num.value += 100 / sum.value;
        pushData.value.push(res.data);
        if (res.data.pushStatus === '1') {
          succeed.value++;
        } else {
          lose.value++;
        }
      }
      saveRecordFn(
        item,
        res,
        '推送',
        JSON.stringify({
          msgId: id,
          code: item.code,
          deviceId: item.deviceId,
          drillPushTotalId,
        }),
        '/drillReportPushLog/logList',
      );
    });
    open5({
      title: '推送进度',
      modalType: 'disabled',
      hideFooter: true,
      serviceApi: async (params: any): Promise<any> => {},
    });
    tableRef.value.refresh();
  }
};

const saveRecordFn = async (
  item: any,
  res: any,
  operateButton: any,
  requestParam: any,
  operateUri: string,
) => {
  const list = [
    {
      deviceCode: item.code,
      operateModule: '推送管理/演练管理/速报演练',
      requestParam,
      status: res.code == 200 ? 1 : 0,
      operateButton,
      operateType: typeEnum.value[operateButton],
      operateUri,
    },
  ];

  await saveRecord({ list });
};

const isInfo = ref();
const cacheHeight = ref(0);
const onAdd = async (record: any) => {
  const params = {
    magnitude: '8',
    focdepth: '20',
    msgType: '',
    addressList: [],
    epiintensity: 0,
  };
  isInfo.value = false;
  mockData.value = [];
  nextTick(() => {
    const dom = document.querySelector('.device_table');
    scrollHeight.value = dom?.getBoundingClientRect().height - 40 || 0;
    if (scrollHeight.value) {
      cacheHeight.value = scrollHeight.value;
    }
  });
  open3({
    title: '新增',
    modalType: 'add',
    defaultValue: {
      ...params,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onView = async (record: any) => {
  isInfo.value = true;
  const res = await getDetails(record.msgId);
  mockData.value = res.data.deviceInfo;

  nextTick(() => {
    const dom = document.querySelector('.device_table');
    scrollHeight.value = dom?.getBoundingClientRect().height - 40 || 0;
    if (scrollHeight.value) {
      cacheHeight.value = scrollHeight.value;
    }
  });
  open3({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: record.pushCount > 0 ? 'disabled' : 'info',
    defaultValue: {
      ...record,
    },
    hasEditPermission: hasPermission('drillReport:edit'),
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const oncancel = (modalType: any, visible: any) => {
  if (modalType.value === 'add') {
    modalType.value = 'info';
    isInfo.value = true;
  } else {
    visible.value = false;
  }
};
const onEdit = (modalType: any) => {
  modalType.value = 'add';
  isInfo.value = false;
};
const onSave = async (form: any, flag: any, push: any) => {
  await formRef.value.validate();
  const { formState } = formRef.value;
  const deviceId = mockData.value.map((item: any) => {
    return item.deviceId;
  });
  const queryParams = { ...formState, deviceId };
  const res = await handleAdd(queryParams);

  if (res.code == 200) {
    flag.value = false;
    sleep(() => tableRef.value.refresh());
  }
  warnKeys.value = [];
  if (push) {
    onPush(null, 'add', res.data.msgId);
  }
};
const mockData = ref([]);

const getRandomChinaCoordinate = () => {
  // 中国经度范围
  var minLng = 90;
  var maxLng = 120;
  // 中国纬度范围
  var minLat = 15;
  var maxLat = 50;

  // 生成随机经度
  var longitude = (Math.random() * (maxLng - minLng) + minLng).toFixed(6);
  // 生成随机纬度
  var latitude = (Math.random() * (maxLat - minLat) + minLat).toFixed(6);
  console.log(formRef.value, 'formModal');
  formRef.value.setFiledValue('epilon', longitude);
  formRef.value.setFiledValue('epilat', latitude);
  getAddressFn(longitude, latitude);
};

const getAddressFn = async (lon: any, lat: any) => {
  const res = await getAddress(lon, lat);
  if (res.code == 200) {
    if (res.msg == '' || res.msg == null) return getRandomChinaCoordinate();
    formRef.value.setFiledValue('locname', res.msg);
  }
};
const selectRef = ref();
const onSelected = (visible: any) => {
  mockData.value = selectList.value;
  visible.value = false;
};

const onRemove = (column, record) => {
  const index = mockData.value.findIndex(
    (i: any) => i.deviceId === record.deviceId,
  );
  warnKeys.value.splice(index, 1);
  mockData.value.splice(index, 1);
};

// processItem(item) {
//             this.objectQuery.project.push(item.id)
//             if (item.children) {
//                 item.children.forEach(this.processItem)
//             }
//         },

const pushData = ref([]);

const pushColumns2 = computed<ProTableProps['columns']>(() => [
  {
    title: '推送状态',
    dataIndex: 'pushStatus',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '站点名称',
    dataIndex: 'siteName',
    align: 'center',
    hideInSearch: true,
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    hideInSearch: true,
    align: 'center',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    hideInSearch: true,
    align: 'center',
  },
]);
const num = ref(0);
const sum = computed(() => {
  return deviceInfo.value.length;
});
const onBack = (visible: any) => {
  visible.value = false;
  tableRef.value.refresh();
};
</script>

<style scoped lang="scss">
.eewMessage {
  > div {
    margin-bottom: 10px;
    display: flex;
    text-align: left;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.custom_title {
  display: flex;
  margin-bottom: 10px;
  justify-content: space-between;
  align-items: center;
}
.process,
.info {
  width: 100%;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}
.process {
  display: flex;
  justify-content: center;
  align-items: center;
  // text-align: center;
  // line-height: 300px;
}
.info {
  padding: 15px 20px;
  margin-top: 20px;
  .title {
    padding: 8px;
    span {
      margin-right: 50px;
      position: relative;
      &:first-child {
        color: #000;
        padding-right: 30px;
        margin-right: 30px;
        border-right: 1px solid #909399;
      }
      &:nth-child(2),
      &:nth-child(3) {
        color: #909399;
        &::before {
          position: absolute;
          top: 50%;
          left: -15px;
          transform: translateY(-50%);
          content: '';
          display: block;
          width: 7px;
          height: 7px;
          border-radius: 50%;
          background-color: #ff0000;
        }
      }
      &:nth-child(3) {
        &::before {
          background: #52c41a;
        }
      }
    }
  }
}
.eewRehearsal_details {
  :deep(.ant-table) {
    height: calc(60vh - 300px);
  }
  :deep(.ant-table-body) {
    height: calc(60vh - 340px);
  }
}
</style>
